import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { ethers } from 'ethers';
import { NetworkConfig } from '../types/types';
import { DEFAULT_NETWORKS } from '../utils/networkUtils';

interface EthersContextType {
    provider: ethers.providers.JsonRpcProvider | null;
    setProvider: (rpcUrl: string) => void;
    currentNetwork: NetworkConfig | null;
}

const EthersContext = createContext<EthersContextType>({
    provider: null,
    setProvider: () => {
        throw new Error('setProvider function must be overridden by provider');
    },
    currentNetwork: null
});

export const EthersProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [provider, setProviderState] = useState<ethers.providers.JsonRpcProvider | null>(null);
    const [currentNetwork, setCurrentNetwork] = useState<NetworkConfig | null>(null);

    // 使用useCallback避免不必要的重渲染
    const setProvider = useCallback((rpcUrl: string) => {
        try {
            const newProvider = new ethers.providers.JsonRpcProvider(rpcUrl);
            setProviderState(newProvider);

            newProvider.getNetwork().then(network => {
                const knownNetwork = DEFAULT_NETWORKS.find(n => n.chainId === network.chainId);
                if (knownNetwork) {
                    setCurrentNetwork(knownNetwork);
                } else {
                    setCurrentNetwork({
                        chainId: network.chainId,
                        name: network.name || 'Custom Network',
                        rpcUrl: rpcUrl,
                        symbol: 'ETH'
                    });
                }
            }).catch(() => {
                setCurrentNetwork({
                    chainId: 0,
                    name: 'Custom Network',
                    rpcUrl: rpcUrl,
                    symbol: 'ETH'
                });
            });
        } catch (error) {
            console.error('Error setting up provider:', error);
            setProviderState(null);
            setCurrentNetwork(null);
        }
    }, []);

    // 初始化默认provider
    useEffect(() => {
        if (DEFAULT_NETWORKS.length > 0) {
            setProvider(DEFAULT_NETWORKS[0].rpcUrl);
        }
    }, [setProvider]);

    return (
        <EthersContext.Provider value={{ provider, setProvider, currentNetwork }}>
            {children}
        </EthersContext.Provider>
    );
};

export const useEthersContext = () => {
    const context = useContext(EthersContext);
    if (!context) {
        throw new Error('useEthersContext must be used within an EthersProvider');
    }
    return context;
};